package google.architecture.coremodel.viewmodel;

import android.app.Application;
import android.databinding.ObservableBoolean;
import android.databinding.ObservableField;
import android.databinding.ObservableInt;
import android.support.annotation.NonNull;

import google.architecture.coremodel.constant.ErrorCode;
import google.architecture.coremodel.datamodel.http.entities.ProductData;
import google.architecture.coremodel.datamodel.http.entities.ShoppingCarItem;
import google.architecture.coremodel.exception.LackOfStockException;
import google.architecture.coremodel.navigator.ProductDetailNavigator;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 保存生命周期和UI所使用的数据
 * Created by dxx on 2017/11/10.
 */

public class ProductDetailViewModel extends PayAndAddShopCarModel {
    //表示当前将要加入购物车的数量
    public final ObservableInt count = new ObservableInt();
    //表示当前将要加入购物车的数量
    public final ObservableInt oldCount = new ObservableInt();
    public final ObservableBoolean reduceEnable = new ObservableBoolean();
    public final ObservableBoolean addEnable = new ObservableBoolean();
    public final ObservableField<ProductData.Product> product = new ObservableField<>();

    public ProductDetailViewModel(@NonNull Application application) {
        super(application);
        count.set(1);
    }

    public void setNavigator(ProductDetailNavigator navigator) {
        super.setNavigator(navigator);
        mNavigator = navigator;
    }

    public void setProduct(ProductData.Product product) {
        this.product.set(product);
        mAutoVenderDataRepository.getItemCount(product.getPlanId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer result) {
                        oldCount.set(result);
                        int left = product.getDrugQuantity() - result;
                        reduceEnable.set(count.get() > 1);
                        addEnable.set(left > count.get());
                    }
                });
    }
}
